package com.jyxd.web.controller.basic;

import com.jyxd.web.data.basic.CommonSetting;
import com.jyxd.web.data.dto.HttpResult;
import com.jyxd.web.data.user.User;
import com.jyxd.web.jobhandler.CustomSyncNurseRecordForm;
import com.jyxd.web.service.assessment.basic.CommonSettingService;
import com.jyxd.web.util.CronUtil;
import com.jyxd.web.util.DateUtil;
import com.jyxd.web.util.HttpCode;
import com.jyxd.web.util.UUIDUtil;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.powerjob.client.PowerJobClient;
import tech.powerjob.common.enums.DispatchStrategy;
import tech.powerjob.common.enums.ExecuteType;
import tech.powerjob.common.enums.ProcessorType;
import tech.powerjob.common.enums.TimeExpressionType;
import tech.powerjob.common.model.LifeCycle;
import tech.powerjob.common.request.http.SaveJobInfoRequest;
import tech.powerjob.common.response.ResultDTO;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/commonSetting")
public class CommonSettingController {

    private static Logger logger = LoggerFactory.getLogger(CommonSettingController.class);

    @Autowired
    private CommonSettingService commonSettingService;

    @Autowired
    private PowerJobClient jobClient;

    /**
     * 增加一条通用设置表记录
     *
     * @return
     */
    @RequestMapping(value = "/insert")
    @ResponseBody
    public String insert(@RequestBody CommonSetting commonSetting) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "添加失败");
        commonSetting.setId(UUIDUtil.getUUID());
        commonSetting.setCreateTime(new Date());
        commonSettingService.insert(commonSetting);
        json.put("code", HttpCode.OK_CODE.getCode());
        json.put("msg", "添加成功");
        return json.toString();
    }

    /**
     * 更新通用设置表记录状态
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "更新失败");
        if (map != null && map.containsKey("id") && map.containsKey("status")) {
            CommonSetting commonSetting = commonSettingService.queryData(map.get("id").toString());
            if (commonSetting != null) {

                commonSettingService.update(commonSetting);
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 编辑通用设置表记录单
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public String edit(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "编辑失败");
        if (map != null && map.containsKey("id") && map.containsKey("status") && map.containsKey("bedName")) {
            CommonSetting commonSetting = commonSettingService.queryData(map.get("id").toString());
            if (commonSetting != null) {

                commonSettingService.update(commonSetting);
                json.put("msg", "编辑成功");
            } else {
                json.put("msg", "编辑失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());

        return json.toString();
    }

    /**
     * 删除通用设置表记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "删除失败");
        if (map.containsKey("id")) {
            CommonSetting commonSetting = commonSettingService.queryData(map.get("id").toString());
            if (commonSetting != null) {

                commonSettingService.update(commonSetting);
                json.put("msg", "删除成功");
            } else {
                json.put("msg", "删除失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据主键id查询通用设置表记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryData", method = RequestMethod.POST)
    @ResponseBody
    public String queryData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("id")) {
            CommonSetting commonSetting = commonSettingService.queryData(map.get("id").toString());
            if (commonSetting != null) {
                json.put("msg", "查询成功");
                json.put("data", JSONObject.fromObject(commonSetting));
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询通用设置表记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("start")) {
            int totalCount = commonSettingService.queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<CommonSetting> list = commonSettingService.queryList(map);
        if (list != null && list.size() > 0) {
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(list));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 增加或更新一条通用设置表记录(排班时间)
     *
     * @return
     */
    @RequestMapping(value = "/updateSchedualTime")
    @ResponseBody
    public String updateSchedualTime(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "添加失败");
        JSONArray array = JSONArray.fromObject(map.get("list").toString());
        if (array != null && array.size() > 0) {
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = (JSONObject) array.get(i);
                if (StringUtils.isNotEmpty(obj.getString("id"))) {
                    //id 不为空则编辑
                    CommonSetting commonSetting = commonSettingService.queryData(obj.getString("id"));
                    commonSetting.setSettingContent(obj.getString("settingContent"));
                    commonSettingService.update(commonSetting);
                } else {
                    //id为空则新增
                    CommonSetting commonSetting = new CommonSetting();
                    commonSetting.setId(UUIDUtil.getUUID());
                    commonSetting.setCreateTime(new Date());
                    commonSetting.setSettingName(obj.getString("settingName"));
                    commonSetting.setSettingContent(obj.getString("settingContent"));
                    commonSetting.setSettingType("排班时间");
                    if ("白班".equals(obj.getString("settingName"))) {
                        commonSetting.setSortNum(1);
                    } else if ("晚班".equals(obj.getString("settingName"))) {
                        commonSetting.setSortNum(2);
                    } else {
                        commonSetting.setSortNum(3);
                    }
                    commonSettingService.insert(commonSetting);
                }
            }
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "添加成功");
        }
        return json.toString();
    }

    /**
     * 查询排班时间的通用设置列表
     *
     * @param map settingType=排班时间
     * @return
     */
    @RequestMapping(value = "/getSchedualTimeList")
    @ResponseBody
    public String getSchedualTimeList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "查询失败");
        List<CommonSetting> list = commonSettingService.getSchedualTimeList(map);
        if (list != null && list.size() > 0) {
            JSONArray array = JSONArray.fromObject(list);
            json.put("data", array);
            json.put("msg", "查询成功");
            json.put("code", HttpCode.OK_CODE.getCode());
        }
        return json.toString();
    }

    /**
     * 新增或更新通用设置表记录(监护仪采集频率)
     *
     * @param commonSetting
     * @return
     */
    @RequestMapping(value = "/updateMonitorFrequency")
    @ResponseBody
    public String updateMonitorFrequency(@RequestBody CommonSetting commonSetting) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "更新失败");
        if (StringUtils.isNotEmpty(commonSetting.getId())) {
            //id不为空 则编辑
            CommonSetting data = commonSettingService.queryData(commonSetting.getId());
            data.setSettingContent(commonSetting.getSettingContent());
            commonSettingService.update(data);
            json.put("msg", "更新成功");
            json.put("code", HttpCode.OK_CODE.getCode());
        } else {
            //id为空则新增
            commonSetting.setSettingName("监护仪采集频率");
            commonSetting.setSettingType("监护仪采集频率");
            commonSetting.setCreateTime(new Date());
            commonSetting.setSortNum(1);
            commonSetting.setId(UUIDUtil.getUUID());
            commonSettingService.insert(commonSetting);
            json.put("msg", "更新成功");
            json.put("code", HttpCode.OK_CODE.getCode());
        }
        return json.toString();
    }

    /**
     * 系统设置--通用设置--监护仪采集频率/默认首页--查询监护仪频率或默认首页
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/getCommonSettingByType")
    @ResponseBody
    public String getCommonSettingByType(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        List<CommonSetting> commonSetting = commonSettingService.getCommonSettingByType(map);
        if (!CollectionUtils.isEmpty(commonSetting)) {
            JSONObject obj = JSONObject.fromObject(commonSetting.get(0));
            json.put("data", obj);
            json.put("msg", "查询成功");
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据病人id查询护理文书同步设置
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/getCommonSettingByPatientId")
    @ResponseBody
    public String getCommonSettingByPatientId(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        List<CommonSetting> commonSetting = commonSettingService.getCommonSettingByPatientId(map);
        if (!CollectionUtils.isEmpty(commonSetting)) {
            JSONObject obj = JSONObject.fromObject(commonSetting.get(0));
            json.put("data", obj);
            json.put("msg", "查询成功");
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }


    /**
     * 新增或更新通用设置表记录(默认首页)
     *
     * @param commonSetting
     * @return
     */
    @RequestMapping(value = "/updateDefaultPage")
    @ResponseBody
    public String updateDefaultPage(@RequestBody CommonSetting commonSetting) throws ParseException {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "更新失败");

        if (StringUtils.isNotEmpty(commonSetting.getId())) {
            //id不为空 则编辑
            CommonSetting data = commonSettingService.queryData(commonSetting.getId());
            if (data != null) {
                if (!StringUtils.equals(commonSetting.getSettingContent(), data.getSettingContent()) ||
                        !StringUtils.equals(commonSetting.getBeginTime(), data.getBeginTime()) ||
                        !StringUtils.equals(commonSetting.getEndTime(), data.getEndTime())) {
                    data.setSettingContent(commonSetting.getSettingContent());
                    data.setBeginTime(commonSetting.getBeginTime());
                    data.setEndTime(commonSetting.getEndTime());

                    if (commonSetting.getSettingType().equals("NursingSynLifeType")) {

                        String oldJobId = commonSetting.getSettingSubType();
                        if (StringUtils.isNotEmpty(oldJobId)) {
                            jobClient.disableJob(Long.parseLong(oldJobId));
                        }
                        SaveJobInfoRequest jobInfoRequest = createJob(commonSetting);
                        ResultDTO<Long> insertJobId = jobClient.saveJob(jobInfoRequest);
                        data.setSettingSubType(String.valueOf(insertJobId.getData()));
                    }

                    commonSettingService.update(data);
                } else if (!StringUtils.equals(data.getOnOff(), commonSetting.getOnOff())) {
                    String oldJobId = data.getSettingSubType();
                    if (StringUtils.isNotEmpty(oldJobId)) {
                        if (StringUtils.equals(commonSetting.getOnOff(), "1")) {
                            logger.info("开启同步生命体征同步任务({}),患者:{}", oldJobId, commonSetting.getPatientId());
                            jobClient.enableJob(Long.parseLong(oldJobId));
                        } else {
                            logger.info("关闭同步生命体征同步任务({}),患者:{}", oldJobId, commonSetting.getPatientId());
                            jobClient.disableJob(Long.parseLong(oldJobId));
                        }
                    }
                    data.setOnOff(commonSetting.getOnOff());
                    commonSettingService.update(data);
                }


                json.put("msg", "更新成功");
                json.put("code", HttpCode.OK_CODE.getCode());
            }
        } else {
            //id为空则新增
            if (commonSetting.getSettingType().equals("NursingSynLifeType")) {
                SaveJobInfoRequest jobInfoRequest = createJob(commonSetting);
                ResultDTO<Long> insertJobId = jobClient.saveJob(jobInfoRequest);
                commonSetting.setSettingSubType(String.valueOf(insertJobId.getData()));
            }
            commonSetting.setCreateTime(new Date());
            commonSetting.setSortNum(1);
            commonSetting.setId(UUIDUtil.getUUID());
            commonSettingService.insert(commonSetting);
            json.put("msg", "新增成功");
            json.put("code", HttpCode.OK_CODE.getCode());
        }

        return json.toString();
    }

    private SaveJobInfoRequest createJob(CommonSetting commonSetting) throws ParseException {
        String cron = CronUtil.createLoopCronExpression(1, Integer.parseInt(commonSetting.getSettingContent()));
        SaveJobInfoRequest jobInfoRequest = new SaveJobInfoRequest();
        jobInfoRequest.setJobName("同步数据到护理单 - 患者:" + commonSetting.getPatientId());
        jobInfoRequest.setJobDescription("同步数据到护理单 - 患者:" + commonSetting.getPatientId());
        jobInfoRequest.setJobParams(commonSetting.getPatientId());
        jobInfoRequest.setDispatchStrategy(DispatchStrategy.HEALTH_FIRST);
        jobInfoRequest.setConcurrency(5);
        jobInfoRequest.setExecuteType(ExecuteType.STANDALONE);
        LifeCycle lifeCycle = new LifeCycle();
        lifeCycle.setStart(DateUtil.yyyyMMddHHmmssSdfToDate(commonSetting.getBeginTime()).getTime());
        lifeCycle.setEnd(DateUtil.yyyyMMddHHmmssSdfToDate(commonSetting.getEndTime()).getTime());
        jobInfoRequest.setLifeCycle(lifeCycle);
        jobInfoRequest.setProcessorType(ProcessorType.BUILT_IN);
        jobInfoRequest.setProcessorInfo(CustomSyncNurseRecordForm.class.getName());
        jobInfoRequest.setTimeExpressionType(TimeExpressionType.CRON);
        jobInfoRequest.setTimeExpression(cron);
        jobInfoRequest.setEnable(StringUtils.equals("1", commonSetting.getOnOff()));
        return jobInfoRequest;
    }

    /**
     * 更新自动同步的开关状态（启动/关闭自动同步）
     *
     * @param commonSetting
     * @return
     */
    @RequestMapping(value = "/updateOnOrOff")
    @ResponseBody
    public String updateOnOrOff(@RequestBody CommonSetting commonSetting) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "更新失败");
        if (commonSetting.getId() == null) {
            json.put("msg", "更新失败，请先保存频率");
            return json.toString();
        }
        boolean flag = commonSettingService.updateOnOrOff(commonSetting);
        if (flag) {
            json.put("msg", "更新成功");
            json.put("code", HttpCode.OK_CODE.getCode());
        }
        return json.toString();
    }


    /**
     * 护理文书生命体征同步开关
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/NursingUpdateOnOrOff", method = RequestMethod.POST)
    @ResponseBody
    public String NursingUpdateOnOrOff(@RequestBody CommonSetting commonSetting, HttpSession session) {
        User user = (User) session.getAttribute("user");
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "更新失败");

        if (commonSetting.getId() == null) {
            commonSetting.setCreateTime(new Date());
            commonSetting.setSortNum(1);
            commonSetting.setId(UUIDUtil.getUUID());
            commonSettingService.insert(commonSetting);
        }
        boolean flag = commonSettingService.NursingUpdateOnOrOff(commonSetting, user);


        if (flag) {
            json.put("msg", "更新成功");
            json.put("code", HttpCode.OK_CODE.getCode());
        }
        return json.toString();
    }

    @ApiOperation("新增或者修改新旧表单全局变量标识")
    @RequestMapping(value = "/updateFormSign", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateFormSign(@RequestBody Map<String, Object> map) {
        return commonSettingService.updateFormSign(map);
    }

}
